package controller

import (
	. "api/model"
	. "api/util"
	"net/http"
	"strconv"
	"github.com/gin-gonic/gin"
)

func CreateCustomer(c *gin.Context) {
	nu := NewUser{}

	err := c.BindJSON(&nu)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	}

	_, err = strconv.Atoi(nu.Phone)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	if len(nu.Phone) != 11 {
		c.JSON(http.StatusOK, gin.H{"error": "手机格式错误"})
		return
	}

	cm := Customer{}
	token, err := cm.CreateCustomer(nu.Phone, nu.SourceUserId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success", "data": PersonInfo{nu.Phone, token}})
}

func CreateCustomerRecord(c *gin.Context) {
	token := c.Request.Header.Get("Token")

	claims, err := ParseCliamsToken(token)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}
	cid := int(claims.Id)

	cr := CustomerRecord{}
	err = c.BindJSON(&cr)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	if cr.ProductType == 0 || cr.ProductId == 0 || cr.SourceCustomer == 0 || cr.Link == "" {
		c.JSON(http.StatusOK, gin.H{"error": "缺少必填参数"})
		return
	}

	cr.CustomerId = cid

	err = cr.CreateCustomerRecord()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}